package com.ruiyi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruiyi.common.Constants;
import com.ruiyi.common.Result;
import com.ruiyi.domain.Account;
import com.ruiyi.dto.AccountDto;
import com.ruiyi.mapper.AccountMapper;
import com.ruiyi.service.AccountService;
import com.ruiyi.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result findLogin(AccountDto accountDto, HttpSession session) {
        /*1验证 验证码是否正确*/
        String redisCode = stringRedisTemplate.opsForValue().get(accountDto.getUsername() + "-" + accountDto.getEmail());
        System.out.println(redisCode);
        System.out.println(accountDto.getCaptcha());
        if(!(accountDto.getCaptcha().equals(redisCode))){
            //显示错误信息
            return new Result(-1,"验证码错误");
        }
        //密码加密
        //对输入的密码进行加密，但是加密过后的密码，还没有保存到数据库的表里面去
        String encry = MD5Util.finalMD5(accountDto.getPwd());
        //将加密过后的密码保存到数据库表里面去
        accountDto.setPwd(encry);
        //登录
        Account account = accountMapper.selectAccountByLogin(accountDto);
        if(account == null){
            return new Result(-1,"用户名或者密码为空");
        }
        //登录成功之后，要将登录的这个人保存到后端缓存数据里面去
        session.setAttribute(Constants.USER_SESSION_KEY,account.getUsername());
        //登录成功之后，要将登录的这个人的角色保存到后端缓存数据里面去
        session.setAttribute(Constants.ROLE_SESSION_KEY,account.getRole());
        //登录成功之后，要将登录的这个人的id保存到后端缓存数据里面去
        session.setAttribute(Constants.USER_SESSION_ID,account.getId());
        Result result = new Result();
        result.setData(account);
        return result;
    }

    @Override
    public Result findAccountsByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Account> accountList = accountMapper.selectAccountsByPage();
        PageInfo<Account> pageInfo = new PageInfo<>(accountList);
        Result result = new Result();
        result.setData(pageInfo.getList());
        result.setTotal(pageInfo.getTotal());
        return result;
    }

    @Override
    public Result modifyAccountStatus(Integer status, Long id,HttpSession session) {
        if(!(status == 0 || status == 1) || id <= 0){
            return Result.DATA_FORMAT_ERROR;
        }
        //判断此操作是否是超级管理员在执行
        String role = session.getAttribute(Constants.ROLE_SESSION_KEY) + "";
        if(!(role.equals("1"))){
            return new Result(-1,"你不是超级管理员，没有此操作权限");
        }
        int i = accountMapper.updateAccountStatus(status,id);
        if(i == 0){
            return new Result(-1,"修改失败!");
        }
        return new Result();
    }

    @Override
    public Result saveAccount(String username,HttpSession session) {
        //只有超级管理员才有添加的权限
        String role = session.getAttribute(Constants.ROLE_SESSION_KEY) + "";
        if(!"1".equals(role)){
            return new Result(-1,"你不是超级管理员，没有此操作的权限");
        }
        //判断账号数据格式是否正确
        if(username == null || !(username.matches("\\w{4,20}"))){
            return Result.DATA_FORMAT_ERROR;
        }
        //判断要添加的账号数据库表里面是否已经存在了
        int n = accountMapper.selectUserNameIsExist(username);
        if(n == 1){
            return new Result(-1,"此账号已经存在");
        }
        int j = accountMapper.insertAccount(username);
        if(j == 0){
            return new Result(-1,"添加失败");
        }
        return new Result();
    }

    @Override
    public Result removeAccountById(Long id,HttpSession session) {
        //只有超级管理员才有添加的权限
        String role = session.getAttribute(Constants.ROLE_SESSION_KEY) + "";
        if(!"1".equals(role)){
            return new Result(-1,"你不是超级管理员，没有此操作的权限");
        }
        //判断是否是超级管理员删除自己
        Object loginUserId = session.getAttribute(Constants.USER_SESSION_ID);
        if(id == Long.parseLong(loginUserId+"")){
            return new Result(-1,"超级管理员不能自己删除自己");
        }
        int i = accountMapper.deleteAccountById(id);
        if(i == 0){
            return new Result(-1,"删除失败");
        }
        return new Result();
    }

    @Override
    public Result modifyResetAccountPwd(Long id,HttpSession session) {
        //只有超级管理员才有添加的权限
        String role = session.getAttribute(Constants.ROLE_SESSION_KEY) + "";
        if(!"1".equals(role)){
            return new Result(-1,"你不是超级管理员，没有此操作的权限");
        }
        //判断是否是超级管理员
        Object loginUserId = session.getAttribute(Constants.USER_SESSION_ID);
        Long rootId = Long.parseLong(loginUserId + "");
        if(rootId == id){
            session.removeAttribute(Constants.USER_SESSION_KEY);
        }
        int i = accountMapper.updateAccount(id);
        if(i == 0){
            return new Result(-1,"密码重置失败");
        }
        return new Result();
    }

    @Override
    public Result modifyAccountPwd(String newPwd,HttpSession session) {
        if(newPwd == null || !(newPwd.matches("\\d{6}"))){
            return Result.DATA_FORMAT_ERROR;
        }
        String userId = session.getAttribute(Constants.USER_SESSION_ID) + "";
        //根据拿到的id,去获取旧密码
        String oldPwd = accountMapper.selectPwdById(userId);
        newPwd = MD5Util.finalMD5(newPwd);
        if(newPwd.equals(oldPwd)){
            return new Result(-1,"密码修改失败，新密码不能和旧密码一样");
        }
        int i = accountMapper.updateAccountPwd(newPwd,userId);
        if(i == 0){
            return new Result(-1,"修改失败");
        }
        session.removeAttribute(Constants.USER_SESSION_KEY);
        return new Result();
    }

    @Override
    public Result modifyAccountImgUrl(String imgUrl, HttpSession session) {
        String userId = session.getAttribute(Constants.USER_SESSION_ID) + "";
        int i = accountMapper.updateAccountImgUrl(imgUrl,Long.parseLong(userId));
        if(i == 0){
            return new Result(-1,"修改头像的后端代码出错");
        }
        return new Result();
    }

}
